
#include <elog.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
#include <elog_file.h>
#include <sys/prctl.h>

 static pthread_mutex_t elog_mutex;

/**
 * EasyLogger port initialize
 *
 * @return result
 */
ElogErrCode elog_port_init(void) {
    ElogErrCode result = ELOG_NO_ERR;

    if (pthread_mutex_init(&elog_mutex, NULL) != 0) {
        result =  ELOG_MUTEX_ERR;
        return result;
    }

    /* add your code here */
    result  =  elog_file_init();
    return result;
}

/**
 * EasyLogger port deinitialize
 *
 */
void elog_port_deinit(void) {

    /* add your code here */
    pthread_mutex_destroy(&elog_mutex);
    elog_file_deinit();
}

/**
 * output log port interface
 *
 * @param log output of log
 * @param size log size
 */
void elog_port_output(const char *log, size_t size) {
    
    /* add your code here */
    /* output to terminal */
    printf("%s", log);
    elog_file_write(log, size);
}

/**
 * output lock
 */
void elog_port_output_lock(void) {
    
    /* add your code here */
    pthread_mutex_lock(&elog_mutex);
}

/**
 * output unlock
 */
void elog_port_output_unlock(void) {
    
    /* add your code here */
    pthread_mutex_unlock(&elog_mutex);
}

static int time_t_to_str(time_t t, char *buf, int len, const char *fmt) {
    struct tm *tm_info;

    tm_info = localtime(&t);
    if (tm_info == NULL) {
        return -1;
    }

    if (strftime(buf, len, fmt, tm_info) == 0) {
        return -1;
    }

    return 0;
}

/**
 * get current time interface
 *
 * @return current time
 */
const char *elog_port_get_time(void) {
    
    /* add your code here */
    time_t now = time(NULL);
    static char buf[64];
    memset(buf,  '0',  sizeof(buf));
    time_t_to_str(now, buf, sizeof(buf), "%Y-%m-%d %H:%M:%S") ;
    return buf;
}

/**
 * get current process name interface
 *
 * @return current process name
 */
const char *elog_port_get_p_info(void) {
    
    /* add your code here */
    const char * pName = "Tel";
    return pName;
}

/**
 * get current thread name interface
 *
 * @return current thread name
 */
const char *elog_port_get_t_info(void) {
    
    /* add your code here */
    static char threadInfo[32];
    static char threadName[16];
    prctl(PR_GET_NAME, threadName);
    snprintf(threadInfo, sizeof(threadInfo), "%s %lu",  threadName,  (unsigned long)pthread_self());
    return threadInfo;
}
